import React, { Component } from 'react';
import _ from 'underscore';

import View from 'lib/View.jsx';
import dispatcher from 'lib/dispatcher';

import Modal from 'lib/components/Modal.jsx';
import {coreApi} from '../apis/core-util';

import AddPolicyItem from './AddPolicyItem.jsx';
import AlertScope from './AlertScope.es6';
import PolicyItem from './PolicyItem.jsx';

export default class AlertEditor extends Modal {
  constructor(props, context) {
    super(props, context);

    this.state.errorMessage = '';
    // this.state.errorMessageWarn = '';
    // this.state.errorMessageAlert = '';
  }

  renderHeader(){
    return (
      <h4>{ this.props.isNew === false ? '编辑告警策略' : '新建告警策略' }</h4>
    )
  } // renderHeader

  renderFooter(){
    return (
      <div>
        <button className="btn-green"
          onClick={ this.handleSubmit.bind(this) }
          type="button">
          保存
        </button>
      </div>
    )
  } // renderFooter

  handleSubmit() {
    // console.log('this', this);
    // console.log('this.state', this.state);
    // console.log('this.state.rule', this.state.rule);
    // console.log('this.scope.options', this.scope.options);

    if (!this.state.alarmName) {
      this.setState({
        errorMessage: '请输入策略名称'
      });
      return false;
    }

    if (this.state.alarmName.length > 400 || this.state.alarmName.length <4) {
      this.setState({
        errorMessage: '策略名称长度范围：4 ~ 400 个字符'
      });
      return false;
    }

    // this.state.rule.map((rule) => {
    //   console.log('rule', rule);
    // });

    let matchedRules = _.chain(this.state.rule).map( rule => [
      //
      rule,
      _.find(this.scope.options, option => option.ruleType === rule.ruleType)
    ]).value();
    // console.log('matchedRules', matchedRules);

    // debugger
    for (var i = 0; i < matchedRules.length; i++) {
      if ((matchedRules[i][0].criteria[0].threshold < matchedRules[i][1].criteria[0].thresholdMin) ||
        (matchedRules[i][0].criteria[1].threshold < matchedRules[i][1].criteria[1].thresholdMin)
        ) {
        return false;
      }
    }

    var { appId } = this.props;
    var alarmNameOri = this.props.alarmName;
    var alarmNameNew = this.state.alarmName;
    // console.log('props', this.props);
    // console.log('alarmNameOri: ', alarmNameOri);
    // console.log('alarmNameNew: ', alarmNameNew);

    if (alarmNameOri === alarmNameNew) {
      // OK
      dispatcher.dispatch({
        $type: 'submit_policy'
      });
    }
    else {
      coreApi({
        urlName:'queryAlarmStrategy',
        appId,
        alarmName:alarmNameNew
      }).fetch().then((policy) => {
        if (_.has(policy, 'appId')) {
          this.setState({
            errorMessage: '此策略名称已存在，请重试'
          });
          return false;
        }
        dispatcher.dispatch({
          $type: 'submit_policy'
        });
      }).fail((policy) =>{
        console.log('Operation failed.');
        // console.log('policy', policy);
        // console.log('policy.responseJSON', policy.responseJSON);
      });
    }

  } // handleSubmit

  onTypeChangeHandler(index, optionIndex) {
    dispatcher.dispatch({
      $type: 'type_changed',
      index,
      optionIndex
    })
  } // onTypeChangeHandler

  onAddTypeHandler() {
    dispatcher.dispatch({
      $type: 'add_type'
    });
  } // onAddTypeHandler

  onCloseHandler(index, label) {
    dispatcher.dispatch({
      $type: 'remove_type',
      index,
      label
    });
  } // onCloseHandler

  handleChangeValue(key, {target}) {
    dispatcher.dispatch({
      $type: 'change_value',
      key,
      value: target.value.trim()
    });
  }

  onPropertyChange(index, key, value) {
    dispatcher.dispatch({
      $type: 'change_rule_value',
      key,
      value,
      index
    });
    // debugger;
  }

  onCriteriaValueChange(index, position, key, value) {
    // console.log(index, position, key, value);
    // console.log(arguments);
    // console.log(arguments.length);
    // console.log('this', this);
    // if (arguments[4] === true) {
    //   return false;
    // }
    dispatcher.dispatch({
      $type: 'change_criteral_value',
      index,
      position,
      key,
      value
    });
  }

  renderBody(){
    let options = _.filter(this.scope.options, (option) => {
      return option.createable === true;
    });

    return (
      <div style={{ width: '1000px' }}>
        <div className="form-group horizontal">
          <ul>
            <li>
              <label htmlFor="policy-name" className="control-label">策略名称：</label>
              <input
                className="input-text"
                style={{ 'borderColor': (this.state.errorMessage !== '') ? 'red': null }}
                id="policy-name"
                value={ this.state.alarmName }
                placeholder="策略名称"
                onChange={ this.handleChangeValue.bind(this, 'alarmName') } />
              <span className="input-addon text-red">*</span>
              <span className="msg-error">{ this.state.errorMessage }</span>
            </li>
            <li className="button-row">
              <label className="control-label">监控项目：</label>
              <button className="mr6 btn-green">APP整体</button>
              <button className="mr6 btn-disabled btn-hollow">网络服务</button>
              <button className="mr6 btn-disabled btn-hollow">页面</button>
              <button className="mr6 btn-disabled btn-hollow">关键元素</button>
            </li>
            <li>
              <label htmlFor="triggerCondition" className="control-label">触发条件：</label>
              <div>
                <span>吞吐量 >=</span>
                <input type="text"
                  className="input-text input-text-80"
                  id="triggerCondition"
                  value={ this.state.cpm }
                  onChange={ this.handleChangeValue.bind(this, 'cpm') } />
                <span className="mr6">cpm</span>
                <i className="iconfont" data-tip="用来限制当被监控的指标项超过设定的阈值时是否触发报警动作的条件。" data-place="right">&#xe663;</i>
              </div>
            </li>
          </ul>
        </div>
        {
          this.state.rule.map((item, index) => {
            return (
              <PolicyItem
               key={ item.ruleType }
               remove={ this.state.rule.length > 1 }
               options={ this.scope.options }
               onClose={ this.onCloseHandler.bind(this, index, item.label) }
               onPropertyChange={ this.onPropertyChange.bind(this, index) }
               onCriteriaValueChange={ this.onCriteriaValueChange.bind(this, index) }
               index={ index } { ...item } />
            );
          })
        }
        {
          options.length > 0
            ? <AddPolicyItem onAdd={ this.onAddTypeHandler } />
            : null
        }
      </div>
    )
  } // renderBody
}

AlertEditor.defaultProps = {
  Scope: AlertScope
}
